package com.zly.framework.rbac.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zly.framework.rbac.model.entity.Role;
import com.zly.framework.rbac.model.entity.RolePermission;
import com.zly.framework.rbac.model.entity.User;
import com.zly.framework.rbac.mapper.RoleMapper;
import com.zly.framework.rbac.service.RolePermissionService;
import com.zly.framework.rbac.service.RoleService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Resource
    private RolePermissionService rolePermissionServiceImpl;

    /**
     * 获取用户的角色
     *
     * @param user 用户
     * @return role
     */
    @Override
    public List<Role> getAllRolesByUserId(User user) {
        return this.baseMapper.getAllRolesByUserId(user);
    }

    /**
     * 分配角色和权限
     *
     * @param roleId        角色id
     * @param permissionIds 权限ids
     */
    @Transactional
    @Override
    public void grantPermission(Long roleId, List<Long> permissionIds) {
        rolePermissionServiceImpl.removeByRoleId(roleId);
        ArrayList<RolePermission> rolePermissions = new ArrayList<>();
        for (Long permissionId : permissionIds) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setPermissionId(permissionId);
            rolePermission.setRoleId(roleId);
            rolePermissions.add(rolePermission);
        }
        rolePermissionServiceImpl.saveBatch(rolePermissions);
    }
}
